<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px" class="search-form">
      <el-form-item label="商家ID" prop="businessId">
        <el-input
          v-model="queryParams.businessId"
          placeholder="请输入商家ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="classId">
        <el-tree-select
          v-model="selectedClassId"
          :data="classTreeData"
          :props="treeProps"
          placeholder="请选择商品分类"
          clearable
          check-strictly
          :render-after-expand="false"
          @change="handleClassChange"
        />
      </el-form-item>
      <el-form-item label="商品价格" prop="goodsPrice">
        <el-input
          v-model="queryParams.goodsPrice"
          placeholder="请输入商品价格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品积分价格" prop="goodsPoint">
        <el-input
          v-model="queryParams.goodsPoint"
          placeholder="请输入商品积分价格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团购价" prop="goodsGroupPrice">
        <el-input
          v-model="queryParams.goodsGroupPrice"
          placeholder="请输入团购价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="折扣价" prop="goodsDiscount">
        <el-input
          v-model="queryParams.goodsDiscount"
          placeholder="请输入折扣价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="秒杀价" prop="goodsMiaosha">
        <el-input
          v-model="queryParams.goodsMiaosha"
          placeholder="请输入秒杀价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品数量" prop="goodsNumber">
        <el-input
          v-model="queryParams.goodsNumber"
          placeholder="请输入商品数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品店内分类id" prop="businessClassId">
        <el-input
          v-model="queryParams.businessClassId"
          placeholder="请输入商品店内分类id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否是虚拟商品" prop="goodsVirtual">
        <el-input
          v-model="queryParams.goodsVirtual"
          placeholder="请输入是否是虚拟商品"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计量单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入计量单位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsStatus">
        <el-select v-model="queryParams.goodsStatus" placeholder="请选择商品状态" clearable>
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="添加商品时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择添加商品时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['lkshop:good:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lkshop:good:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lkshop:good:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['lkshop:good:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="商家ID" align="center" prop="businessId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品分类ID" align="center" prop="classId" />
      <el-table-column label="商品价格" align="center" prop="goodsPrice" />
      <el-table-column label="商品积分价格" align="center" prop="goodsPoint" />
      <el-table-column label="是否是积分商品(0-否,1-是)" align="center" prop="goodsPointType" />
      <el-table-column label="是否折扣(0-否,1-是)" align="center" prop="goodsDiscountType" />
      <el-table-column label="是否秒杀(0-否,1-是)" align="center" prop="goodsKillType" />
      <el-table-column label="是否团购(0-否,1-是)" align="center" prop="goodsGroupType" />
      <el-table-column label="团购价" align="center" prop="goodsGroupPrice" />
      <el-table-column label="折扣价" align="center" prop="goodsDiscount" />
      <el-table-column label="秒杀价" align="center" prop="goodsMiaosha" />
      <el-table-column label="商品状态" align="center" prop="goodsStatus" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.goodsStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center" prop="goodsNumber" />
      <el-table-column label="商品图片" align="center" prop="goodsImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.goodsImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品视频" align="center" prop="goodsVideo" />
      <el-table-column label="商品店内分类id" align="center" prop="businessClassId" />
      <el-table-column label="是否是虚拟商品" align="center" prop="goodsVirtual" />
      <el-table-column label="计量单位" align="center" prop="unit" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lkshop:good:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lkshop:good:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商家ID" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入商家ID" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类ID" prop="classId">
          <el-input v-model="form.classId" placeholder="请输入商品分类ID" />
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品积分价格" prop="goodsPoint">
          <el-input v-model="form.goodsPoint" placeholder="请输入商品积分价格" />
        </el-form-item>
        <el-form-item label="团购价" prop="goodsGroupPrice">
          <el-input v-model="form.goodsGroupPrice" placeholder="请输入团购价" />
        </el-form-item>
        <el-form-item label="折扣价" prop="goodsDiscount">
          <el-input v-model="form.goodsDiscount" placeholder="请输入折扣价" />
        </el-form-item>
        <el-form-item label="秒杀价" prop="goodsMiaosha">
          <el-input v-model="form.goodsMiaosha" placeholder="请输入秒杀价" />
        </el-form-item>
        <el-form-item label="商品数量" prop="goodsNumber">
          <el-input v-model="form.goodsNumber" placeholder="请输入商品数量" />
        </el-form-item>
        <el-form-item label="商品状态" prop="goodsStatus">
          <el-switch
            v-model="form.goodsStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsImg">
          <image-upload v-model="form.goodsImg"/>
        </el-form-item>
        <el-form-item label="商品视频" prop="goodsVideo">
          <file-upload v-model="form.goodsVideo"/>
        </el-form-item>
        <el-form-item label="商品店内分类id" prop="businessClassId">
          <el-input v-model="form.businessClassId" placeholder="请输入商品店内分类id" />
        </el-form-item>
        <el-form-item label="是否是虚拟商品" prop="goodsVirtual">
          <el-input v-model="form.goodsVirtual" placeholder="请输入是否是虚拟商品" />
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入计量单位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Good">
import { listGood, getGood, delGood, addGood, updateGood, getGood_classTree } from "@/api/lkshop/good"

const { proxy } = getCurrentInstance()

const goodList = ref([])
const classTreeData = ref([])
const selectedClassId = ref(null)
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: null,
    goodsName: null,
    classId: null,
    goodsPrice: null,
    goodsPoint: null,
    goodsPointType: null,
    goodsDiscountType: null,
    goodsKillType: null,
    goodsGroupType: null,
    goodsGroupPrice: null,
    goodsDiscount: null,
    goodsMiaosha: null,
    goodsStatus: null,
    goodsNumber: null,
    goodsImg: null,
    goodsVideo: null,
    businessClassId: null,
    goodsVirtual: null,
    unit: null,
    createTime: null
  },
  rules: {
    businessId: [
      { required: true, message: "商家ID不能为空", trigger: "blur" }
    ],
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    classId: [
      { required: true, message: "商品分类ID不能为空", trigger: "blur" }
    ],
    goodsPrice: [
      { required: true, message: "商品价格不能为空", trigger: "blur" }
    ],
    goodsStatus: [
      { required: true, message: "商品状态(0-下架,1-上架)不能为空", trigger: "change" }
    ],
    goodsNumber: [
      { required: true, message: "商品数量不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询商品管理列表 */
function getList() {
  loading.value = true
  listGood(queryParams.value).then(response => {
    goodList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    goodsId: null,
    businessId: null,
    goodsName: null,
    classId: null,
    goodsPrice: null,
    goodsPoint: null,
    goodsPointType: null,
    goodsDiscountType: null,
    goodsKillType: null,
    goodsGroupType: null,
    goodsGroupPrice: null,
    goodsDiscount: null,
    goodsMiaosha: null,
    goodsStatus: null,
    goodsNumber: null,
    goodsImg: null,
    goodsVideo: null,
    businessClassId: null,
    goodsVirtual: null,
    unit: null,
    createTime: null
  }
  proxy.resetForm("goodRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  selectedClassId.value = null
  queryParams.value.classId = null
  handleQuery()
}

/** 商品分类选择变化 */
function handleClassChange(value) {
  if (value) {
    // 如果选择了分类，将选择的分类ID设置到查询参数中
    queryParams.value.classId = value;
  } else {
    queryParams.value.classId = null;
  }
  console.log('选择的分类ID:', value);
}

/** 查询商品分类树形结构 */
function getClassTreeData() {
  getGood_classTree({}).then(response => {
    console.log('商品分类树形数据:', response.data);
    classTreeData.value = response.data || [];
  }).catch((error) => {
    console.error('获取商品分类树形数据失败:', error);
    classTreeData.value = [];
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.goodsId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _goodsId = row.goodsId || ids.value
  getGood(_goodsId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodRef"].validate(valid => {
    if (valid) {
      if (form.value.goodsId != null) {
        updateGood(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGood(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _goodsIds = row.goodsId || ids.value
  proxy.$modal.confirm('是否确认删除商品管理编号为"' + _goodsIds + '"的数据项？').then(function() {
    return delGood(_goodsIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 处理商品状态变更 */
function handleStatusChange(row) {
  const text = row.goodsStatus === 1 ? '上架' : '下架';
  updateGood(row).then(() => {
    proxy.$modal.msgSuccess(`商品${text}成功`);
  }).catch(() => {
    // 如果更新失败，回滚状态
    row.goodsStatus = row.goodsStatus === 1 ? 0 : 1;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('lkshop/good/export', {
    ...queryParams.value
  }, `good_${new Date().getTime()}.xlsx`)
}

getList()
getClassTreeData()
</script>

<style scoped>
/* 搜索表单样式 */
.search-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 15px;
  margin-right: 20px;
}

.search-form :deep(.el-input) {
  width: 200px;
}

.search-form :deep(.el-select) {
  width: 200px;
}

.search-form :deep(.el-date-picker) {
  width: 200px;
}

/* 表头样式 */
:deep(.el-table th) {
  background: #409eff !important;
  color: #ffffff !important;
  font-weight: 600;
  font-size: 14px;
  text-align: center;
}

:deep(.el-table th .cell) {
  color: #ffffff !important;
}

/* 表格整体样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

:deep(.el-table tbody tr:hover) {
  background: #f8f9fa;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
}

/* 开关样式 */
:deep(.el-switch) {
  margin: 0 5px;
}

/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  font-size: 14px;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #409eff;
  color: #ffffff;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: #409eff;
  color: #ffffff;
}
</style>
